package datastruct.sort;

import java.util.Arrays;

/**
 * @program: DataStructuresAndAlgorithms
 * @description: 快排
 * @author: zhang
 * @create: 2020-03-13 13:36
 */
public class QuickSortDemo {

    public static void quickSort(int[] arr, int left, int right) {
        int l = left; //左下标
        int r = right;//右下标
        //pivot 中轴
        int pivot = arr[(left + right) / 2];
        //
        int temp = 0;
        while (l < r) {
            while (arr[l] < pivot) {
                l += 1;
            }
            while (arr[r] > pivot) {
                r -= 1;
            }
            //如果l>=r说明pivot的左右两边的值，已经按照左边全部是
            // 小于pivot的值，右边是全部大于等于pivot的值
            if (l >= r) {
                break;
            }
            //交换
            temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;
            if (arr[l] == pivot) {
                r -= 1;
            }
            if (arr[r] == pivot) {
                l += 1;
            }


        }
        if (l == r) {
            l += 1;
            r -= 1;
        }
        if (left < r) {
            quickSort(arr, left, r);
        }
        if (right > l) {
            quickSort(arr, l, right);
        }
    }

    public static void main(String[] args) {
//        int[] arr = {1, 2, 7, 3, 0, 4, 9, 2, 4, 22, 21, 20};
//        int[] arr = new int[80000];
//        for (int i = 0; i < arr.length; i++) {
//            arr[i] = (int) (Math.random() * 8000000);
//        }
        int[] arr = {1, 2, 6, 4, 5};

        long start = System.currentTimeMillis();

        quickSort(arr, 0, arr.length - 1);
        System.out.println(System.currentTimeMillis() - start);

        System.out.println(Arrays.toString(arr));
    }
}